package com.p7.architect.store.product.infrastructure.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.p7.architect.store.common.page.PageUtils;
import com.p7.architect.store.common.page.PagePlus;
import com.p7.architect.store.common.page.TableDataInfo;
import com.p7.architect.store.product.domain.data.dto.StockDto;
import com.p7.architect.store.product.domain.data.vo.StockVo;
import org.springframework.stereotype.Service;
import com.p7.architect.store.common.mybatisplus.core.ServicePlusImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.p7.architect.store.product.infrastructure.domain.StockDo;
import com.p7.architect.store.product.infrastructure.mapper.StockMapper;
import com.p7.architect.store.product.infrastructure.service.IStockService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 商品库存Service业务层处理
 *
 * @ClassName: IStockServiceImpl
 * @author dengbicheng
 * @date 2022-07-06
 */
@Service
public class StockServiceImpl extends ServicePlusImpl<StockMapper, StockDo, StockVo> implements IStockService {

    @Override
    public StockVo queryById(Long id){
        return getVoById(id);
    }

    @Override
    public TableDataInfo<StockVo> queryPageList(StockDto dto) {
        PagePlus<StockDo, StockVo> result = pageVo(PageUtils.buildPagePlus(), buildQueryWrapper(dto));
        return PageUtils.buildDataInfo(result);
    }

    @Override
    public List<StockVo> queryList(StockDto dto) {
        return listVo(buildQueryWrapper(dto));
    }

    private LambdaQueryWrapper<StockDo> buildQueryWrapper(StockDto dto) {
        Map<String, Object> params = dto.getParams();
        LambdaQueryWrapper<StockDo> lqw = Wrappers.lambdaQuery();
        lqw.eq(dto.getSkuId()!=null, StockDo::getSkuId, dto.getSkuId());
        return lqw;
    }

    @Override
    public Boolean insertByDto(StockDto dto) {
        StockDo add = BeanUtil.toBean(dto, StockDo.class);
        validEntityBeforeSave(add);
        boolean flag = save(add);
        if (flag) {
            dto.setId(add.getId());
        }
        return flag;
    }

    @Override
    public Boolean updateByDto(StockDto dto) {
        StockDo update = BeanUtil.toBean(dto, StockDo.class);
        validEntityBeforeSave(update);
        return updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(StockDo entity){
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return removeByIds(ids);
    }
}
